package controllers

import (
	"egin/app/request"
	"egin/app/service"
	"egin/pkg/redigo"
	"egin/pkg/response"
	"egin/pkg/vali"
	"encoding/json"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
)

func XmSelectList(c *gin.Context) {
	list, err := service.XmSelectList()
	if err == nil {
		response.SuccessWithData(list, c)
	} else {
		response.ErrorWithMessage("服务器错误", c)
	}
}

//RoleIndexHtml 角色列表页
func RoleIndexHtml(c *gin.Context) {

	c.HTML(http.StatusOK, "role/index.tmpl", nil)
}

//RoleCreateHtml 添加角色页面
func RoleCreateHtml(c *gin.Context) {
	c.HTML(http.StatusOK, "role/create.tmpl", nil)
}

//RoleEditHtml 修改角色页面
func RoleEditHtml(c *gin.Context) {
	role, _ := service.GetRole(c)
	roleJson, err := json.Marshal(role)
	if err != nil {
		zap.L().Error("RoleEditHtml json err", zap.Error(err))
	}

	c.HTML(http.StatusOK, "role/edit.tmpl", gin.H{"role": string(roleJson)})
}

//RoleIndex  获取角色列表数据
func RoleIndex(c *gin.Context) {

	list, err := service.GetRoleList(c)
	if err == nil {
		response.SuccessWithData(list, c)
	} else {
		response.ErrorWithMessage("服务器错误", c)
	}
}

//RoleCreate 添加角色
func RoleCreate(c *gin.Context) {

	var param request.RoleQs

	if err := c.ShouldBind(&param); err != nil {
		errStr := vali.ValidErrMsg(&param, err.(validator.ValidationErrors))
		response.ErrorWithMessage(errStr, c)
		return
	}

	err := service.RoleAdd(param, c)
	if err == nil {
		response.SuccessWithMessage("添加成功", c)
	} else {
		response.ErrorWithMessage("添加失败", c)
	}
}

//RoleEdit 修改角色
func RoleEdit(c *gin.Context) {
	var param request.RoleEditQs
	if err := c.ShouldBind(&param); err != nil {
		errStr := vali.ValidErrMsg(&param, err.(validator.ValidationErrors))
		response.ErrorWithMessage(errStr, c)
		return
	}

	err := service.RoleEdit(param, c)
	if err == nil {
		conn := redigo.GetPool().Get()
		defer conn.Close()
		conn.Do("del", "admin_rbac")
		conn.Do("del", "admin_menu")
		response.SuccessWithMessage("修改成功", c)
	} else {
		response.ErrorWithMessage("修改失败", c)
	}
}

func RoleDelete(c *gin.Context) {
	err := service.RoleDelete(c)
	if err == nil {
		conn := redigo.GetPool().Get()
		defer conn.Close()
		conn.Do("del", "admin_rbac")
		conn.Do("del", "admin_menu")
		response.SuccessWithMessage("删除成功", c)
	} else {
		response.ErrorWithMessage(err.Error(), c)
	}
}
